import React, { Component } from "react";
import {
  Text,
  View,
  TouchableOpacity,
  Dimensions,
  NativeAppEventEmitter,
  NativeEventEmitter,
  NativeModules,
  Platform,
  StatusBar,
  TouchableWithoutFeedback,
} from "react-native";
import { connect } from "react-redux";

import * as theme from "theme";
import { getStore, setStore } from "utils";
// import record from "assets/images/record.png";
import { WhiteSpace, Toast } from "@ant-design/react-native";
import Icon from "components/Iconfont";
import Loading from "components/Loading";
// import AudioRecord from "components/AudioRecord";
import TopNavBarNoBottomLine from "components/TopNavBarNoBottomLine";

import WaterView from "../../../components/WaterView";
import SearchListView from "../component/SearchListView";

import CenterTab from "../../mine/opinionFeedback/components/Tabs";

import styles from "./styles";

const { RNRecognizer, iOSModule } = NativeModules;

const { height: windowHeight } = Dimensions.get("window");

// let _audioRecordRef = null;
class AudioSearch extends Component {
  constructor(props) {
    super(props);
    this._tabs2 = {
      1: {
        key: 1,
        label: global.lang.home.putonghua,
      },
      2: {
        key: 2,
        label: global.lang.home.yueyu,
      },
    };
    this.state = {
      isShow: true,
      open: false,
      current: this._tabs2[1].key,
      _tabs: this._tabs2,
      loadingText: global.lang.home.sayTxt,
      loading: "",
      resultText: "",
      isLoading: true,
    };
    this._waterView = null;
  }

  componentWillMount() {
    StatusBar.setBarStyle("dark-content");

    // 权限问题 客户端自己集成判断
    if (this.failedSubscription) this.failedSubscription.remove();
    this.failedSubscription = NativeAppEventEmitter.addListener(
      "onFailed",
      data => {
        // console.log(data);
        this.setState({ resultText: `${data.status}:${data.code}` });
      }
    );
    if (this.progressSubscription) this.progressSubscription.remove();
    this.progressSubscription = NativeAppEventEmitter.addListener(
      "onChange",
      data => {
        // this.onChange(data);
        const msgs = data.msg;
        const json = JSON.parse(msgs);
        const { payload } = json;
        if (payload) {
          this.setState({ resultText: `${payload.result}` });
        }
      }
    );

    if (this.finishedSubscription) this.finishedSubscription.remove();
    if (Platform.OS === "android") {
      this.finishedSubscription = NativeAppEventEmitter.addListener(
        "onCompleted",
        data => {
          const msgs = data.msg;
          const json = JSON.parse(msgs);
          const { payload } = json;
          if (payload) {
            this.setState({ resultText: `${payload.result}` });
            this.historyOnSend(payload.result);
          }
        }
      );
    } else {
      const calendarManagerEmitter = new NativeEventEmitter(
        NativeModules.iOSModule
      );
      this.finishedSubscription = calendarManagerEmitter.addListener(
        "onCompleted",
        data => {
          if (data.payload.result) {
            this.setState({ loadingText: data.payload.result });
            this.historyOnSend(data.payload.result);
          }
        }
      );
    }

    // 默认普通话
    getStore("setRecType").then(index => {
      const { _tabs } = this.state;
      let res = 1;
      if (index === "yuyue") {
        res = 2;
        this.onTabChange(_tabs[res].key, _tabs[res]);
      } else {
        // eslint-disable-next-line no-param-reassign
        res = 1;
        this.onTabChange(_tabs[res].key, _tabs[res]);
      }
      this.setState({ isLoading: false });
      console.log("切换识别:", _tabs[res].label); // eslint-disable-line
    });
  }

  componentWillUnmount() {
    if (this.failedSubscription) this.failedSubscription.remove();
    if (this.progressSubscription) this.progressSubscription.remove();
    if (this.finishedSubscription) this.finishedSubscription.remove();
    if (Platform.OS === "android") {
      RNRecognizer.stopRecognizer(msg => {
        // console.log("invoke:", msg);
      });
      RNRecognizer.release();
    } else {
      iOSModule.stopRecognizer();
    }
  }

  onPressIn = () => {
    const { open } = this.state;

    console.log("按下");
    this.setState({ isShow: true });
    this._waterView.start();
    if (open) {
      if (Platform.OS === "android") {
        // 调用识别
        RNRecognizer.startRecognizer(msg => {
          console.log("invoke:", msg);
          this.setState({
            loadingText: null,
            loading: global.lang.home.loadingTxt,
          });
        });
      } else {
        iOSModule.startRecognizer();
        this.setState({
          loadingText: null,
          loading: global.lang.home.loadingTxt,
        });
      }
    } else {
      Toast.info("配置未正确", 1);
    }
  };

  onPressOut = () => {
    console.log("松开");
    this._waterView.stop();
    this.setState({ isShow: false });

    if (Platform.OS === "android") {
      // 停止录音返回文件并跳转提交
      // _audioRecordRef.stop();
      // _audioRecordRef.upload();
      RNRecognizer.stopRecognizer(msg => {
        console.log("invoke:", msg);
        this.setState({ loadingText: global.lang.home.sayTxt, loading: "" });
      });
    } else {
      iOSModule.stopRecognizer();
      this.setState({ loadingText: global.lang.home.sayTxt, loading: "" });
    }

    // _audioRecordRef.stop().then(res => {
    //   // RNAACToPCM
    //   const ToastKey = Toast.loading("转换中。。。", 3);
    //   res.filePath = `/sdcard/danpaiche.aac`;
    //   res.pcmPath = `/sdcard/test2222.pcm`;
    //   RNAACToPCM.toPCM(res.filePath, res.pcmPath, msg => {
    //     Portal.remove(ToastKey);
    //     console.log(msg);
    //     if (msg && msg.status === "OK") {
    //       this.upload(msg.audioFileURL);
    //     } else {
    //       Toast.info(msg.des, 1);
    //     }
    //   });
    //   // this.upload(res);
    // });
  };

  // upload = filePath => {
  //   const ToastKey = Toast.loading("识别中。。。", 0);
  //   const { dispatch } = this.props;
  //   const form = new FormData();
  //   form.append("file", {
  //     file: `${filePath}`,
  //     type: `audio/*`,
  //     name: `test_${Date.now()}.pcm`,
  //   });
  //   dispatch({
  //     type: "home/uploadAudio",
  //     payload: { form },
  //   }).then(res => {
  //     if (res !== null) {
  //       // resolve(null);
  //       Portal.remove(ToastKey);
  //       Toast.success("上传成功", 1);
  //     }
  //   });
  // };

  back = () => {
    const { navigation } = this.props;
    return (
      <TouchableOpacity
        onPress={() => {
          if (navigation && typeof navigation.goBack === "function")
            navigation.pop();
        }}
      >
        <Icon name="close" color={theme.ColorFontBase} size={20} />
      </TouchableOpacity>
    );
  };

  right = () => {
    return (
      <View style={styles.right}>
        <TouchableOpacity onPress={() => {}} style={{ marginRight: 10 }}>
          <Icon name="hope" type="icon" color={theme.ColorFontBase} size={20} />
        </TouchableOpacity>
      </View>
    );
  };

  historyOnSend = val => {
    const { navigation, dispatch } = this.props;
    if (val && val !== "") {
      dispatch({
        type: "public/buryingPoint",
        payload: {
          behavior: `语音识别:${val}`,
        },
      });
      navigation.navigate("MostSearch", { keyWord: val });
    }
  };

  onTabChange = (key, tab) => {
    this.setState({ current: tab.key }, () => {
      if (key === 1) {
        const { homeData } = this.props;
        const { appinfo: res } = homeData;
        if (res !== null) {
          // resolve(null);
          if (Platform.OS === "android") {
            RNRecognizer.init(
              res.appKey,
              res.token,
              res.url,
              res.vocabularyId,
              msg => {
                if (msg === "ok") {
                  this.setState({ open: true });
                }
              }
            );
          } else {
            iOSModule.stopRecognizer();
            iOSModule.initWithappKey(
              res.appKey,
              res.token,
              res.url,
              res.vocabularyId
            );
            this.setState({ open: true });
          }
          setStore("setRecType", "putonghua");
        }
      } else {
        const { homeData } = this.props;
        const { appinfo: res } = homeData;
        if (res !== null) {
          console.log("粤语", res.cantonUrl);
          if (Platform.OS === "android") {
            RNRecognizer.init(
              res.appKey,
              res.token,
              res.cantonUrl,
              res.cantonVocabularyId,
              msg => {
                if (msg === "ok") {
                  this.setState({ open: true });
                }
              }
            );
          } else {
            iOSModule.stopRecognizer();
            iOSModule.initWithappKey(
              res.appKey,
              res.token,
              res.cantonUrl,
              res.cantonVocabularyId
            );
            this.setState({ open: true });
          }
          setStore("setRecType", "yuyue");
        }
      }
    });
  };

  render() {
    const {
      isShow,
      loadingText = "",
      loading,
      resultText,
      current,
      _tabs,
      isLoading,
    } = this.state;
    const { navigation, dispatch } = this.props;
    return (
      <View style={styles.root}>
        <View
          style={{
            width: "100%",
            height: windowHeight - 350,
            // backgroundColor: "#F4F5F5",
          }}
        >
          <TopNavBarNoBottomLine
            navigation={navigation}
            leftText={this.back()}
            midText=""
            // rightText={this.right()}
          />
          <View style={styles.panel}>
            {/* 菜单 */}
            <WhiteSpace />
            <Text style={styles.subTitle}>{global.lang.home.welTxt}</Text>
            <WhiteSpace />
          </View>

          <SearchListView
            navigation={navigation}
            dispatch={dispatch}
            historyOnSend={this.historyOnSend}
          />
          {/* 这个组件的aac格式 阿里识别不了故只做单纯录音文件播放用了 */}
          {/* <AudioRecord
            ref={ref => {
              _audioRecordRef = ref;
            }}
          /> */}
        </View>
        {isLoading && <Loading />}
        <Text
          style={{
            height: 100,
            fontSize: 22,
            color: "#28354C",
            lineHeight: 32,
            alignItems: "center",
          }}
        >
          {resultText || ""}
        </Text>
        <View
          style={{
            width: "100%",
            height: 150,
            alignItems: "center",
            // backgroundColor: "#F4F5F5",
          }}
        >
          <Text>{loadingText || loading}</Text>
          <TouchableWithoutFeedback
            onPressIn={() => {
              this.onPressIn();
            }}
            onPressOut={() => {
              this.onPressOut();
            }}
          >
            <View
              style={{
                height: 150,
                marginBottom: 100,
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <View style={{ opacity: isShow ? 1 : 0 }}>
                <WaterView
                  style={{
                    height: 150,
                    width: 150,
                  }}
                  ref={waterView => {
                    this._waterView = waterView;
                  }}
                />
              </View>

              <View style={{ position: "absolute", top: 25, zIndex: 100 }}>
                <View
                  style={{
                    width: 100,
                    height: 100,
                    alignSelf: "center",
                    alignItems: "center",
                    borderRadius: 60,
                    backgroundColor: "#0A74E8",
                  }}
                >
                  <Icon
                    style={{ marginVertical: 21 }}
                    name="voice"
                    type="icon"
                    size={45}
                    color={theme.ColorBackgroundComp}
                  />
                </View>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
        <View style={{ height: 100, width: "100%" }}>
          <CenterTab
            style={{
              marginLeft: "30%",
              paddingHorizontal: 16,
            }}
            ccolor="#000"
            csize={22}
            current={current}
            tabs={Object.values(_tabs)}
            onChange={this.onTabChange}
          />
        </View>

        {/* <WaterView auto /> */}
      </View>
    );
  }
}

export default connect(stores => ({
  homeData: stores.home,
  missionData: stores.mission,
}))(AudioSearch);
